package com.schoolvisitors.service;

import com.alibaba.fastjson2.JSONObject;
import com.schoolvisitors.entity.LoginToken;
import com.schoolvisitors.entity.RegisterToken;
import com.schoolvisitors.entity.User;
import com.schoolvisitors.repository.RegisterTokenRepository;
import com.schoolvisitors.repository.LoginTokenRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
public class AuthService {
    private final WeChatService weChatService;
    private final UserService userService;
    private final LoginTokenRepository loginTokenRepository;
    private final RegisterTokenRepository registerTokenRepository;

    public AuthService(WeChatService weChatService, UserService userService, LoginTokenRepository loginTokenRepository, RegisterTokenRepository registerTokenRepository) {
        this.weChatService = weChatService;
        this.userService = userService;
        this.loginTokenRepository = loginTokenRepository;
        this.registerTokenRepository = registerTokenRepository;
    }

    public JSONObject auth(String code) {
        // 获取用户的 WeChat User ID
        String weChatUserId = weChatService.getUserId(code);

        // 进行数据库查询，查找是否存在该用户
        User user = userService.findByWeChatUserId(weChatUserId);
        if (user == null) {
            RegisterToken rt = new RegisterToken();
            rt.setToken(makeToken());
            rt.setWechatUserId(weChatUserId);
            log.info("{} {}", rt.getToken(), weChatUserId);
            registerTokenRepository.save(rt);
            JSONObject json = new JSONObject();
            json.put("type", "register");
            json.put("token", rt.getToken());
            return json;
        }

        String tokenString = makeToken();
        LoginToken loginToken = new LoginToken();
        loginToken.setRole("user");
        loginToken.setToken(tokenString);
        loginToken.setIndexId(user.getId());
        loginToken.setCreateTime(LocalDateTime.now());
        loginTokenRepository.save(loginToken);

        // 返回用户信息和 loginToken
        JSONObject response = new JSONObject();
        response.put("type", "login");
        response.put("token", tokenString);
        response.put("userId", user.getId());
        return response;
    }


    private String makeToken(){
        return UUID.randomUUID().toString().replace("-", "").substring(0, 32);
    }
}
